package com.ming.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ming.common.CodeMsg;
import com.ming.common.Constant;
import com.ming.common.Result;
import com.ming.common.exception.BussiException;
import com.ming.common.realm.ActiveUser;
import com.ming.domain.Book;
import com.ming.domain.SysUser;
import com.ming.from.BookRentForm;
import com.ming.mapper.BookMapper;
import com.ming.mapper.SysUserMapper;
import com.ming.query.BookRentQuery;
import com.ming.query.SysUserQuery;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.domain.BookRent;
import com.ming.mapper.BookRentMapper;
import com.ming.service.BookRentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 *@Author:何元才
 *@Desc:
 *@data:2021-04-27 15:23
 */
@Service
public class BookRentServiceImpl extends ServiceImpl<BookRentMapper, BookRent> implements BookRentService{


    @Autowired
    private BookRentMapper bookRentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 分页查询借阅记录
     *
     * @param query
     * @return
     */
    @Override
    public Result queryPage(BookRentQuery query) {

        //拿到最大时间 最小时间段
        if (StrUtil.isNotBlank(query.getCreateTime())) {
            String[] split = query.getCreateTime().split("~");
            query.setMinCreateTime(split[0].trim());
            query.setMaxCreateTime(split[1].trim());
        }

        //开启分页查询
        Page<BookRent> page = new Page<>(query.getPage(),query.getLimit());
        Page<BookRent> bookRentPage = bookRentMapper.selectPage(page, new LambdaQueryWrapper<BookRent>()
                .eq(!ObjectUtils.isEmpty(query.getHandlerId()), BookRent::getHandlerId, query.getHandlerId())
                .eq(StringUtils.hasText(query.getRent_name()), BookRent::getRentName, query.getRent_name())
                .eq(!ObjectUtils.isEmpty(query.getPhone()), BookRent::getPhone, query.getPhone())
                .between(!ObjectUtils.isEmpty(query.getCreateTime()), BookRent::getCreateTime, query.getMinCreateTime(), query.getMaxCreateTime())
        );
        return new Result(bookRentPage);
    }

    /**
     * 借阅图书
     *
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result rent(BookRentForm form) {
        //检验用户的合法性
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhone, form.getPhone())
        );
        if (sysUser == null){
            return new Result(CodeMsg.USER_NOT_EXIST_ERROR);
        }
        //查询书籍状态 如果书籍状态不是 可借阅 则返回
        Book book = bookMapper.selectById(form.getBookId());
        if (!(book.getIsRent()).equals(Constant.RENT_UN)){
            return new Result(CodeMsg.BOOK_NOT_RENT_ERROR);
        }
        String rentTime = form.getRentTime();
        String[] split = rentTime.split("~");
        form.setBeginTime(split[0].trim());
        form.setEndTime(split[1].trim());

        //设置操作者ID 获取当前用户 状态 创建时间 修改时间
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        form.setHandlerId(activeUser.getSysUser().getId());
        form.setState(0);
        form.setCreateTime(new Date());
        form.setUpdateTime(new Date());
        //1.新增借阅记录
        BookRent bookRent = new BookRent();
        BeanUtils.copyProperties(form,bookRent);
        bookRentMapper.insert(bookRent);  //新增失败 需要回滚
        //2.改变书籍状态  并且获取受影响的行数
        //别看了，config里面和domain里面对vesion加了乐观锁
        book.setIsRent(Constant.RENT_ED);
        int m = bookMapper.updateById(book);
        if (m == 0){
            //抛异常回滚数据
            throw new BussiException(CodeMsg.BOOK_STATE_CHANGE_ERROR.code,CodeMsg.BOOK_STATE_CHANGE_ERROR.msg);
        }
        return new Result();
    }
}
